<!-- 充值产品购买 -->
<template>
  <view class="bigbox">
    <view class="topbox">
      <view class="btbox">
        <view style="margin-right: 12rpx">
          <u-image :src="brandCover" width="50rpx" height="50rpx"></u-image>
        </view>
        <view>{{ brandName }}</view>
      </view>
      <view class="smallbox">
        <view class="bt" style="margin-bottom: 20rpx">充值账号</view>
        <view
          class="nr"
          style="
            background-color: #fff;
            height: 150rpx;
            border-radius: 10rpx;
            padding: 20rpx;
          "
        >
          <view style="color: #fe513f">
            <u-icon name="info-circle" color="#FE513F"></u-icon
            >请确保账号无误，充值成功后不支持退换
          </view>
          <u-input
            placeholder="请输入充值账号"
            clearable
            type="number"
            v-model="phoneNum"
            focus
          ></u-input>
        </view>
      </view>
      <view class="smallbox">
        <view class="bt">充值类型</view>
        <view class="nr nr2">
          <view
            class="lxbox"
            v-for="(ele, index) in lxList"
            :key="index"
            :class="activeIndex == index ? 'activelx' : ''"
            @click="handleClickLx(index)"
          >
            {{ ele.productName }}
            <view v-if="activeIndex == index" class="tbbox">
              <u-image
                src="./static/xztb.png"
                width="35rpx"
                height="35rpx"
              ></u-image>
            </view>
          </view>
        </view>
      </view>
      <view class="smallbox">
        <view class="bt">充值面额</view>
        <view class="nr nr3">
          <view
            class="jqbox"
            v-for="(ele2, index) in lxList[activeIndex]?.faceValue"
            :key="index"
            :class="activeIndex2 == index ? 'activejq' : ''"
            @click="handleClickJq(ele2, index)"
          >
            <view style="font-size: 24rpx">
              {{ ele2.rechargeDenomination }}
            </view>
            <view style="font-size: 28rpx; font-weight: 500; color: #fe5644">
              售价￥{{ ele2.userPayMoney }}
            </view>
            <view class="yjbox hswz"> 官方价 ￥{{ ele2.officialPrice }} </view>
            <view v-if="activeIndex2 == index" class="tbbox">
              <u-image
                src="./static/xztb.png"
                width="42rpx"
                height="42rpx"
              ></u-image>
            </view>
          </view>
        </view>
      </view>
      <view class="smallbox" style="padding-top: 0px" v-if="useExplain">
        <view style="font-size: 26rpx">充值说明</view>
        <view class="nr">
          <view v-html="useExplain"></view>
        </view>
      </view>
    </view>
    <view class="footerbox">
      <view class="txbox">
        <view class="jgwz">可用{{ flqTicket }}复来券，商品最多抵扣 </view>
        <view class="jgwz" style="display: flex; align-items: center">
          - ￥
          <text class="price2">{{
            lxList[activeIndex]?.faceValue[activeIndex2]?.userScoreMoney || 0
          }}</text>
          <!-- <u-input
            style="width: 100rpx"
            :height="'10rpx'"
            :border="true"
            class="inputBox"
            v-input-decimal
            placeholder="请输入抵扣的金额"
            type="digit"
            v-model="discountInput"
            @blur="handleDkInput"
          /> -->
        </view>
      </view>
      <view class="txbox" style="margin-bottom: 20rpx; height: 45rpx">
        <view>服务费</view>
        <view
          >￥{{
            lxList[activeIndex]?.faceValue[activeIndex2]?.handleFee || 0
          }}</view
        >
      </view>
      <view class="txbox txbox2">
        <view class="kuai">
          合计<text class="jgwz"
            >￥{{
              lxList[activeIndex]?.faceValue[activeIndex2]?.userPayMoney || 0
            }}</text
          >
        </view>
        <view class="kuai">
          <u-button type="primary" size="default" @click="handlePayBtn"
            >立即购买</u-button
          >
        </view>
      </view>
    </view>
  </view>
</template>
<script setup lang="ts">
import { reactive, ref, computed, nextTick, watch } from 'vue'
import { onLoad, onReady } from '@dcloudio/uni-app'
import { enumAll, orderApi, directApi, moneyApi } from '@/api'
import { storeToRefs } from 'pinia'
import { browserVersion, isMobile } from '@/utils/common'
import { useUserStore, useShopInfoStore } from '@/store'

const userStore = useUserStore()
const shopStore = useShopInfoStore()
const { accessToken, useShareCode, userInfo } = storeToRefs(userStore)
const isApp = ref(false)
const orderData = ref<any>({})
const phoneNum = ref()
const discountInput = ref(1)
const brandName = ref()
const brandCover = ref()
const activeIndex = ref(0)
const activeIndex2 = ref(-1)
const lxList = ref<any>([])
const flqTicket = ref()
const useExplain = ref()

onLoad(async (option: any) => {
  isApp.value = shopStore.isApp
  const options = JSON.parse(option.product)
  brandCover.value = options.brandCover
  brandName.value = options.brandName
  handleGetBtList(options.brandName)
  getDiscountTicket()
  // console.log(userInfo.value,1111)
  phoneNum.value = userInfo.value.phone
})
const handleDkInput = (e: number) => {
  e = Number(e)
  // if (e <= scoreMax.value) {
  //     cldyqInput.value = e
  //   } else {
  //     cldyqInput.value = scoreMax.value
  //     uni.showToast({
  //       icon: 'none',
  //       title: `最多可抵扣长来抵用券￥${scoreMax.value}`
  //     })
  //   }
}
// 获取当前产品列表
const handleGetBtList = async (brandName: string) => {
  try {
    const params = {
      brandName,
      shopMode: 4
    }
    const { data } = await directApi
      .getListByBrandNameApi(params)
      .finally(() => {
        uni.hideLoading()
      })
    lxList.value = data.products
    // console.log(data, '所有分类数据')
  } catch (error) {
    console.log('获取分类error', error)
  }
}
// 获取当前类型及面额详情
const handleproductDetail = async (productNo: number) => {
  try {
    const params = {
      productNo
    }
    const { data } = await directApi.getProductDetailApi(params).finally(() => {
      uni.hideLoading()
    })
    useExplain.value = data.useExplain
    // console.log(data, '所有分类数据')
  } catch (error) {
    console.log('获取分类error', error)
  }
}
// 点击类型
const handleClickLx = (index: number) => {
  activeIndex.value = index
}
// 点击面额
const currentData = ref()
const handleClickJq = async (row: any, index: number) => {
  activeIndex2.value = index
  handleproductDetail(row.productNo)
  currentData.value = row
}
const getOrderMoney = async () => {
  const obj = {}
  // console.log('创建money需要的数据', obj)
  uni.showLoading({ title: '折扣计算中请稍后', mask: true })
  try {
    const { data } = await orderApi.orderMoney(obj).finally(() => {
      uni.hideLoading()
    })
  } catch (e) {
    console.log('获取ordermoney错误', e)
  }
}
const getDiscountTicket = async () => {
  try {
    // 复来券模式
    const { data } = await moneyApi.getMemberTotalFulaiquan()
    flqTicket.value = data
  } catch (error: any) {
    console.log(error)
    uni.showToast({
      title: '获取优惠券失败' + error.msg,
      icon: 'none'
    })
    flqTicket.value = 0
  }
}
const handlePayBtn = async () => {
  if (!phoneNum.value)
    return uni.showToast({ title: '请输入充值账号', icon: 'none' })
  if (!isMobile(phoneNum.value))
    return uni.showToast({ title: '请输入正确的手机号！', icon: 'none' })
  if (activeIndex2.value == -1)
    return uni.showToast({ title: '请选择充值面额', icon: 'none' })
  uni.showModal({
    title: '提示',
    content: `您将向 ${phoneNum.value} 充值,确定吗？`,
    confirmText: '确认',
    cancelText: '取消',
    success: async ({ confirm, cancel }) => {
      if (confirm) {
        submit()
      }
    }
  })
}
const submit = async () => {
  orderData.value = {
    orderProductSkus: [
      {
        count: 1,
        shopProductSkuId: '91918',
        money: currentData.value.price
      }
    ],
    status: 10,
    productNo: currentData.value.productNo,
    contactNumber: phoneNum.value,
    integralsRuleId: 9,
    scoreMoney: currentData.value.userScoreMoney
  }
  const { data } = await orderApi.orderMoney(orderData.value)
  // console.log('创建订单准备数据==》', orderData.value)
  uni.showLoading({ title: '加载中', mask: true })
  orderData.value.userId = data.userId
  orderData.value.orderProductSkus[0].dynamicPric = true
  try {
    const { data } = await orderApi.orderAdd(orderData.value).finally(() => {
      uni.hideLoading()
    })
    // console.log('orderAdd返回', data)
    if (data) {
      if (isApp.value) {
        const u = browserVersion()
        if (u.iPhone) {
          // @ts-ignore
          window.JSBridge.invoke('goPay', {
            orderId: data.id,
            money: data.payMoney
          })
          shopStore.setIsApp(false)
          return
        } else if (u.isAndroid) {
          // @ts-ignore
          if (window?.Android) {
            // @ts-ignore
            window?.Android?.goPay(data.id, data.payMoney)
            shopStore.setIsApp(false)
          }
          return
        }
      } else {
        location.href = `https://api.mylkjgs.com/?token=${accessToken.value}&orderId=${data.id}`
      }
    }
  } catch (e) {
    console.log('获取orderadd错误', e)
  }
}
</script>
<style lang="scss" scoped>
.bigbox {
  font-size: 24rpx;
  background: linear-gradient(
    to bottom,
    #f9dcb8 5%,
    #faead7 25%,
    #f8f8f8 85%,
    #f5f5f5 100%
  );
  min-height: 100vh;
  .topbox {
    padding-bottom: 300rpx;
    .btbox {
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 32rpx;
      padding: 24rpx 24rpx 0;
      color: #333;
    }
    .smallbox {
      padding: 20rpx;
      // margin-bottom: 20rpx;
      .bt {
        font-size: 28rpx;
        font-weight: 500;
        margin-bottom: 20rpx;
      }
      .nr {
        > view {
          margin-bottom: 10rpx;
          color: #333;
        }
      }
      .nr2 {
        display: grid;
        grid-template-columns: repeat(auto-fill, 48%);
        justify-content: space-between;
        .lxbox {
          background-color: #fff;
          // width: 90%;
          height: 100rpx;
          padding: 20rpx;
          line-height: 60rpx;
          border: 1rpx solid #dbdbdb;
          text-align: center;
          border-radius: 10rpx;
          position: relative;
          .tbbox {
            position: absolute;
            right: -3rpx;
            bottom: 1rpx;
          }
        }
        .activelx {
          border: 3rpx solid #fe5744;
        }
      }
      .nr3 {
        display: flex;
        align-items: center;
        justify-content: space-between;
        flex-wrap: wrap;
        .jqbox {
          background-color: #fff;
          padding: 20rpx;
          text-align: center;
          width: 48%;
          border: 1rpx solid #dbdbdb;
          margin-bottom: 20rpx;
          border-radius: 10rpx;
          position: relative;
          .yjbox {
            text-decoration: line-through;
          }
          .tbbox {
            position: absolute;
            right: -2rpx;
            bottom: -3rpx;
          }
        }
        .activejq {
          border: 3rpx solid #fe5744;
        }
      }
    }
  }
  .footerbox {
    padding: 20rpx 20rpx 40rpx;
    background: #ffffff;
    box-shadow: 0rpx -4rpx 16rpx 4rpx rgba(0, 0, 0, 0.1);
    position: fixed;
    bottom: 0;
    width: 100%;
    .txbox {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 10rpx;
    }
    .txbox2 {
      .kuai {
        width: 50%;
        height: 80rpx;
        line-height: 80rpx;
        font-size: 35rpx;
        text-align: left;
        border-radius: 10rpx;
      }
    }
  }
}
.overwz {
  //   单行文本省略号
  width: 100%;
  white-space: nowrap; /* 禁止文本换行 */
  overflow: hidden; /* 隐藏溢出内容 */
  text-overflow: ellipsis; /* 用省略号表示被截断的文本 */
}
.hswz {
  color: #999;
  font-size: 20rpx;
}
.jgwz {
  color: #fe5644;
  .price2 {
    font-size: 30rpx;
    font-weight: 700;
  }
}
</style>
